<?php

require_once 'Ftp/Adapter/Interface.php';

require_once 'Ftp/Adapter/Ftp.php';

require_once 'Ftp/Directory.php';

class Skjb_Ftp
{
    protected $config = array(
        'adapter' => 'Skjb_Ftp_Adapter_Ftp',
    );
    
    protected $adapter = null;
    
    private $_currentPath = null;
    
    private $_currentDirectory = null;

    public function __construct($config = null)
    {
        if ($config !== null) {
            $this->setConfig($config);
        }
    }
    
    public function setConfig($config = array())
    {
        if ($config instanceof Zend_Config) {
            $config = $config->toArray();

        } elseif (! is_array($config)) {
            throw new Exception('Array or Zend_Config object expected, got ' . gettype($config));
        }

        foreach ($config as $k => $v) {
            $this->config[strtolower($k)] = $v;
        }

        // Pass configuration options to the adapter if it exists
        if ($this->adapter instanceof Skjb_Ftp_Adapter_Interface) {
            $this->adapter->setConfig($config);
        }

        return $this;
    }
    
    public function getCurrentDirectory()
    {
        if ($this->_currentDirectory == null) {
            if ($this->_currentPath == null) {
                $this->_currentPath = $this->getAdapter()->getCurrentPath();
            }
            $this->_currentDirectory = new Skjb_Ftp_Directory($this->_currentPath, $this);
        }
        
        return $this->_currentDirectory;
    }

    public function setAdapter($adapter)
    {
        if (is_string($adapter)) {
            $adapter = new $adapter;
        }

        if (! $adapter instanceof Skjb_Ftp_Adapter_Interface) {
            throw new Exception('Passed adapter is not a valid FTP connection adapter');
        }

        $this->adapter = $adapter;
        $config = $this->config;
        unset($config['adapter']);
        $this->adapter->setConfig($config);
    }

    public function getAdapter()
    {
        if ($this->adapter == null) {
            $this->setAdapter($this->config['adapter']);
        }

        return $this->adapter;
    }
    
    public function changeDir($path)
    {
        $this->getAdapter()->changeDir($path);
        
        $this->_currentPath = $path;
    }
}